package com.ratingbay.cjob;

import java.io.File;
import java.io.IOException;
import java.util.Timer; 
import javax.servlet.ServletContextEvent;  
import javax.servlet.ServletContextListener;

import org.apache.commons.io.FileUtils;

import com.ratingbay.cjob.tasks.*;
import com.ratingbay.console.common.RatingBayConst;

public class SysContextListener implements ServletContextListener {
    
    private Timer timer = null;

    @Override
    public void contextInitialized(ServletContextEvent event){
        //在这里初始化监听器，在tomcat启动的时候监听器启动，可以在这里实现定时器功能
        timer = new Timer(true);
        
        //60*60*1000表示一个小时
        timer.schedule( new GameSummaryCal(event.getServletContext()), 60*1000*60*24, 60*1000*60*24);
        timer.schedule( new LinkTweetCountCal(event.getServletContext()), 60*1000*60*24, 60*1000*60*24);
        timer.schedule( new LuceneMergeCal(event.getServletContext()), 60*1000*60*24, 60*1000*60*24);
        timer.schedule( new TweetLinkCal(event.getServletContext()), 60*1000*60*24, 60*1000*60*24);
        timer.schedule( new TweetTimeCal(event.getServletContext()), 60*1000*60*24, 60*1000*60*24);
        //全量index 
        if("YES".equals(RatingBayConst.LUCENE_REINDEX)){
        	try {
				FileUtils.deleteDirectory(new File(RatingBayConst.LUCENE_FILE_PATH));
			} catch (IOException e) {
				e.printStackTrace();
			}
        	timer.schedule( new LuceneIndexCal(event.getServletContext()), 1*1000*60, 2*1000*60);
        }
        else{
        	timer.schedule( new LuceneAppendIndexCal(event.getServletContext()), 10*1000*60, 10*1000*60);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent event){
        //在这里关闭监听器，所以在这里销毁定时器。  
        if(timer != null){
            timer.cancel();
        }
    }
}